package top.lishuoboy.jwt.session.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.lishuoboy.jwt.session.bean.User;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author lishuoboy
 * @date 2022/4/18 11:49
 */
@Slf4j
@Controller
public class LoginController {
    /* 初始化用户数据 */
    private static final Map<String, User> userMap = MapUtil.<String, User>builder()
        .put("zhangsan", new User("zhangsan", "111111"))
        .put("lisi", new User("lisi", "222222"))
        .build();


    @GetMapping("/login")
    @ResponseBody
    private String login(User user, HttpSession session) {
        String name = user.getName();
        if (!userMap.containsKey(name)) {
            return "用户【" + name + "】不存在";
        }
        if (!userMap.get(name).getPwd().equals(user.getPwd())) {
            return "用户【" + name + "】密码错误";
        }
        session.setAttribute("user", user);
        return "用户【" + user.getName() + "】登录成功。" + RandomUtil.randomInt(10000);
    }

    @GetMapping("/logout")
    @ResponseBody
    private String logout(HttpSession session) {
        session.setAttribute("user", null);
        return "当前用户已登出";
    }

    @GetMapping("/main")
    @ResponseBody
    private String main(HttpSession session) {
        return session.getAttribute("user") == null ? "当前用户未登录" : "当前用户已登录";
    }
}
